<template>
	<div class="flex flex-column flex-align-center flex-justify-center page">
		<audio ref="audio" :src="notifyUrl" controls muted="true" @ended="onAudioEnded" />
		<i v-if="off" class="el-icon-turn-off-microphone" @click="handlePlay" />
		<i v-else class="el-icon-microphone" />
	</div>
</template>
<script>
import notifyMp3 from "@/assets/notify.mp3";
export default {
	data() {
		return {
			off: true,
			autoplay: false,
			isEnded: false,
			notifyUrls: [],
			notifyUrl: "",
			timer: null
		};
	},
	sockets: {
		// 连接成功
		connect() {
			console.log("socket已连接");
			// this.$socket.emit("login", { token: this.token });
			const { event, ...args } = this.$route.query;
			let evt = event || "new_deposit";
			this.$ws.emit(evt, args);
		},
		ping(data) {
			// console.log("this is ping");
			// this.$socket.emit("pong", data);
			this.$ws.emit("pong", data);
		},
		pong(data) {
			console.log("this is pong", data);
		},
		error() {
			// console.log("this is error", data);
			this.$ws?.reconnect?.();
		},
		// 断开连接回调
		disconnect() {
			console.log("socket已断开");
			// this.$ws.reconnect();
		}
	},
	mounted() {
		window.$depositNotify = this;
		this.$nextTick(() => {
			const { event } = this.$route.query;
			let evt = event || "new_deposit";
			this.sockets?.subscribe?.(evt, data => {
				console.log("evt", evt);
				this.play(data.fileName);
			});
			this.$once("hook:beforeDestroy", () => {
				clearTimeout(this.timer);
				this.sockets?.unsubscribe?.(evt);
			});
		});
	},
	methods: {
		handlePlay() {
			if (!this.off) return;
			if (this.isEnded) return;
			this.off = false;
			this.$refs.audio.muted = false;
			let isEmpty = this.notifyUrls.length == 0;
			this.autoplay = true;
			this.play(isEmpty ? notifyMp3 : null);
		},
		play(url) {
			clearTimeout(this.timer);
			if (url) {
				this.notifyUrls.push(url);
			}
			if (!this.autoplay) return;
			if (!this.notifyUrls.length) return;
			if (this.isEnded) return;
			this.isEnded = true;
			this.notifyUrl = this.notifyUrls.shift();
			this.$nextTick(() => {
				this.$refs.audio?.play?.();
			});
			console.log("play", this.notifyUrl);
		},
		// 播放结束
		onAudioEnded() {
			this.isEnded = false;
			this.notifyUrl = "";
			this.timer = setTimeout(() => {
				this.play();
			}, 3000);
			console.log("onAudioEnded");
		}
	}
};
</script>
<style lang="scss" scoped>
.page {
	height: 90%;
	font-size: 100px;
	color: #868e9f;
	audio {
		opacity: 0;
	}
}
</style>
